//
//  LGSelectDateView.m
//  LGSanofiPatient
//
//  Created by 1234 on 2022/10/20.
//

#import "LGSelectDateView.h"
#import "FSCalendarAppearance.h"
#import "FSCalendar.h"

@interface LGSelectDateView()<FSCalendarDelegate,FSCalendarDataSource,FSCalendarDelegateAppearance>
/**   */
@property (nonatomic , strong)FSCalendar *calendar;
/**   */
@property (nonatomic , strong)UIView *baseView;
/**   */
@property (nonatomic , strong)UIButton *backButton;
/**   */
@property (nonatomic , strong)UILabel *titleLabel;
/**   */
@property (nonatomic , strong)UIView *selectView;
/**   */
@property (nonatomic , strong)UIButton *leftBtn;
/**   */
@property (nonatomic , strong)UIButton *rightBtn;
/**   */
@property (nonatomic , strong)UILabel *dateLabel;
/**  有日程 */
@property (nonatomic , strong)UIButton *scheduleBtn;
/**  有逾期 */
@property (nonatomic , strong)UIButton *overdueBtn;
/**   */
@property (nonatomic , strong)NSDateFormatter *monthFormatter;
/**   */
@property (nonatomic , strong)NSDateFormatter *dayFormatter;
/**   */
@property (nonatomic , strong)NSMutableArray *eventArray;
/**   */
@property (nonatomic , assign)NSInteger currentYear;
/**   */
@property (nonatomic , assign)NSInteger currentMonth;
@end

@implementation LGSelectDateView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        NSString *monthStr = [self.monthFormatter stringFromDate:[NSDate date]];
        self.currentYear = [[monthStr substringToIndex:4] integerValue];
        self.currentMonth = [[monthStr substringWithRange:NSMakeRange(5, 2)] integerValue];
        [self createSubView];
        [self.calendar selectDate:[NSDate date]];
    }
    return self;
}

-(void)showCalenderViewAnimation{
    self.hidden = NO;
    [UIView animateWithDuration:0.4 animations:^{
        self.baseView.alpha = 1;
        self.backgroundColor = [UIColor colorWithString:@"#0D0D0D" alpha:0.7];
//        self.baseView.frame = CGRectMake(0, Screen_H-viewPix(440), Screen_W, viewPix(460));
    }];
}

-(void)closeBtnAction{
    [UIView animateWithDuration:0.4 animations:^{
        self.baseView.alpha = 0;
        self.backgroundColor = [UIColor colorWithString:@"#0D0D0D" alpha:0];
//        self.baseView.frame = CGRectMake(0, Screen_H, Screen_W, viewPix(460));
    } completion:^(BOOL finished) {
        self.hidden = YES;
//        [self removeFromSuperview];
    }];
}

-(void)setPointArray:(NSArray *)pointArray{
    _pointArray = pointArray;
    self.eventArray = [NSMutableArray array];
    for (NSInteger i=0; i<pointArray.count; i++) {
        NSString *answerTime = LGNSString(pointArray[i][@"answerTime"]);
        [self.eventArray addObject:answerTime];
    }
    [self.calendar reloadData];
}

//上个月 、下个月
-(void)monthBtnAction:(UIButton *)sender{
    NSDate *currentPatent = self.calendar.currentPage;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:(NSCalendarUnitMonth | NSCalendarUnitYear) fromDate:currentPatent];
    
    if (sender == self.leftBtn) {
        [components setMonth:components.month-1];
    }else{
        [components setMonth:components.month+1];
    }
    currentPatent = [calendar dateFromComponents:components];
    [self.calendar setCurrentPage:currentPatent animated:YES];
    self.dateLabel.text = [self.monthFormatter stringFromDate:currentPatent];
    
    NSInteger year = [[self.dateLabel.text substringToIndex:4] integerValue];
    NSInteger month = [[self.dateLabel.text substringWithRange:NSMakeRange(5, 2)] integerValue];
    
    if(self.delegate && [self.delegate respondsToSelector:@selector(monthRecordWithYear:month:)]){
        [self.delegate monthRecordWithYear:year month:month];
    }
    
    if(year<self.currentYear || (year == self.currentYear && month<self.currentMonth)){
        self.rightBtn.userInteractionEnabled = YES;
        self.rightBtn.selected = NO;
    }else{
        self.rightBtn.userInteractionEnabled = NO;
        self.rightBtn.selected = YES;
    }
}


//eventPoint数量
-(NSInteger)calendar:(FSCalendar *)calendar numberOfEventsForDate:(NSDate *)date{
    NSString *dateStr = [self.dayFormatter stringFromDate:date];
    if ([self.eventArray containsObject:dateStr]) {
        return 1;
    }
    return 0;
}

//event图片
- (nullable NSArray *)calendar:(FSCalendar *)calendar imageArrayForDate:(NSDate *)date{
    return @[@"日历-事件"];
}

//点击选中日期
- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition{
    if (date == calendar.today) {
        calendar.appearance.titleTodayColor = [UIColor colorWithString:@"#FFFFFF"];
    }else{
        calendar.appearance.titleTodayColor = [UIColor colorWithString:@"#2B2A37"];
    }
    NSString *dateStr = [self.dayFormatter stringFromDate:date];
    if (self.delegate && [self.delegate respondsToSelector:@selector(selectDate:)]) {
        [self.delegate selectDate:dateStr];
    }
    [self closeBtnAction];
}

//滑动、切换月份后默认选中日期
- (void)calendarCurrentPageDidChange:(FSCalendar *)calendar{
    self.dateLabel.text = [self.monthFormatter stringFromDate:calendar.currentPage];
    if (calendar.currentPage == calendar.today) {
        calendar.appearance.titleTodayColor = [UIColor colorWithString:@"#FFFFFF"];
    }else{
        calendar.appearance.titleTodayColor = [UIColor colorWithString:@"#2B2A37"];
    }
//    [calendar selectDate:calendar.currentPage];
}

#pragma mark
#pragma mark ====> 创建控件
-(void)createSubView{
    self.hidden = YES;
    self.titleLabel.text = @"选择记录时间";
    self.backgroundColor = [UIColor colorWithString:@"#0D0D0D" alpha:0];
    [self addSubview:self.baseView];
    [self.baseView addSubview:self.titleLabel];
    [self.baseView addSubview:self.backButton];
    [self.baseView addSubview:self.selectView];
    [self.selectView addSubview:self.dateLabel];
    [self.selectView addSubview:self.leftBtn];
    [self.selectView addSubview:self.rightBtn];
    [self.baseView addSubview:self.calendar];
    [self.baseView addSubview:self.scheduleBtn];
    [self.baseView addSubview:self.overdueBtn];
    
    [self.dateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.centerY.equalTo(self.selectView);
    }];
    [self.leftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.dateLabel.mas_left).offset(-viewPix(23));
        make.width.height.equalTo(@(viewPix(30)));
        make.centerY.equalTo(self.selectView);
    }];
    [self.rightBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.dateLabel.mas_right).offset(viewPix(23));
        make.centerY.width.height.equalTo(self.leftBtn);
    }];
    [self.scheduleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.calendar.mas_bottom);
        make.right.equalTo(self.mas_centerX).offset(-viewPix(15));
        make.width.equalTo(@(viewPix(70)));
        make.height.equalTo(@(viewPix(22)));
    }];
    [self.overdueBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.mas_centerX).offset(viewPix(15));
        make.centerY.width.height.equalTo(self.scheduleBtn);
    }];
}

-(UIView *)baseView{
    if(!_baseView){
        _baseView = [[UIView alloc]initWithFrame:CGRectMake(0, -15, Screen_W, viewPix(335)+topBarHeight+15)];
        _baseView.backgroundColor = [UIColor colorWithString:@"#FEFEFF"];
        _baseView.cornerRidus = 15;
        _baseView.alpha = 0;
        CAGradientLayer *gradLayer = [[CAGradientLayer alloc]init];
        gradLayer.frame = CGRectMake(0, 0, Screen_W ,viewPix(370)+topBarHeight+15);
        gradLayer.startPoint = CGPointMake(0.5, 0);
        gradLayer.endPoint = CGPointMake(0.5, 1.0);
        gradLayer.colors = @[(__bridge id)[UIColor colorWithString:@"#E0F0FF"].CGColor, (__bridge id)[UIColor colorWithString:@"#F3F9FE"].CGColor, (__bridge id)[UIColor colorWithString:@"#FEFEFF"].CGColor];
        gradLayer.locations = @[@(0), @(0.5), @(1.0f)];
        gradLayer.cornerRadius = 20;
        [_baseView.layer addSublayer:gradLayer];
    }
    return _baseView;
}

-(UIButton *)backButton{
    if(!_backButton){
        _backButton = [UIButton buttonWithImage:@"navBack" selectImage:@"navBack"];
        _backButton.frame = CGRectMake(0, statusBarHeight+15, 44, 44);
        [_backButton addTarget:self action:@selector(closeBtnAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backButton;
}

-(UILabel *)titleLabel{
    if(!_titleLabel){
        _titleLabel = [UILabel lableWithText:@"全部日程" colorString:@"#333333" textFont:LGFontWeight(16, UIFontWeightSemibold) textAlignment:NSTextAlignmentCenter lines:1];
        _titleLabel.frame = CGRectMake(viewPix(100), statusBarHeight+15, Screen_W-viewPix(200), 44);
    }
    return _titleLabel;
}

-(UIView *)selectView{
    if(!_selectView){
        _selectView = [[UIView alloc]initWithFrame:CGRectMake(0, topBarHeight+viewPix(12)+15, Screen_W, viewPix(30))];
        _selectView.backgroundColor = [UIColor whiteColor];
    }
    return _selectView;
}

-(UILabel *)dateLabel{
    if(!_dateLabel){
        _dateLabel = [UILabel lableWithText:[self.monthFormatter stringFromDate:[NSDate date]] colorString:@"#2B2A37" textFont:LGFontWeight(16, UIFontWeightMedium) textAlignment:NSTextAlignmentCenter lines:1];
    }
    return _dateLabel;
}

-(UIButton *)leftBtn{
    if(!_leftBtn){
        _leftBtn = [UIButton buttonWithImage:@"日历-上个月" selectImage:@"日历-上个月"];
        [_leftBtn addTarget:self action:@selector(monthBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _leftBtn;
}

-(UIButton *)rightBtn{
    if(!_rightBtn){
        _rightBtn = [UIButton buttonWithImage:@"日历-下个月" selectImage:@"日历-下个月"];
        [_rightBtn addTarget:self action:@selector(monthBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightBtn;
}


-(FSCalendar *)calendar{
    if(!_calendar){
        _calendar = [[FSCalendar alloc]initWithFrame:CGRectMake(viewPix(20), kMaxY(self.selectView.frame), Screen_W-viewPix(40), viewPix(255))];
        _calendar.backgroundColor = [UIColor clearColor];
        _calendar.headerHeight = 0;//设置顶部显示月份的高度
        _calendar.weekdayHeight = viewPix(40);
        _calendar.rowHeight = viewPix(30);
        _calendar.locale = [NSLocale localeWithLocaleIdentifier:@"zh-CN"];
        [_calendar setScope:FSCalendarScopeMonth animated:NO];
        _calendar.appearance.todayColor = [UIColor clearColor];
        _calendar.appearance.caseOptions = FSCalendarCaseOptionsWeekdayUsesSingleUpperCase;
        _calendar.appearance.weekdayFont = LGFont(16);
        _calendar.appearance.weekdayTextColor = [UIColor colorWithString:@"#666666"];
        _calendar.appearance.titleFont = LGFont(18);
        _calendar.appearance.titleDefaultColor = [UIColor colorWithString:@"#444444"];
        _calendar.appearance.titlePlaceholderColor = [UIColor colorWithString:@"#A9A8B6"];
        _calendar.appearance.titleSelectionColor = [UIColor colorWithString:@"#3291FF"];
        _calendar.appearance.selectionColor = [UIColor colorWithString:@"#DFEEFF"];
        _calendar.appearance.eventDefaultColor = [UIColor colorWithString:@"#009B77"];
        _calendar.appearance.eventSelectionColor = [UIColor colorWithString:@"#FFFFFF"];
        _calendar.dataSource = self;
        _calendar.delegate = self;
    }
    return _calendar;
}

-(UIButton *)scheduleBtn{
    if(!_scheduleBtn){
        _scheduleBtn = [UIButton buttonWithTitle:@" 有日程" titleFont:LGFont(16) textColor:@"#666666" imageName:@"日程-有日程"];
        _scheduleBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        _scheduleBtn.userInteractionEnabled = NO;
    }
    return _scheduleBtn;
}

-(UIButton *)overdueBtn{
    if(!_overdueBtn){
        _overdueBtn = [UIButton buttonWithTitle:@" 有逾期" titleFont:LGFont(16) textColor:@"#666666" imageName:@"日程-有逾期"];
        _overdueBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _overdueBtn.userInteractionEnabled = NO;
    }
    return _overdueBtn;
}

-(NSDateFormatter *)monthFormatter{
    if(!_monthFormatter){
        _monthFormatter = [[NSDateFormatter alloc]init];
        _monthFormatter.dateFormat = @"yyyy年MM月";
    }
    return _monthFormatter;
}

-(NSDateFormatter *)dayFormatter{
    if(!_dayFormatter){
        _dayFormatter = [[NSDateFormatter alloc]init];
        _dayFormatter.dateFormat = @"yyyy-MM-dd";
    }
    return _dayFormatter;
}

-(void)drawDashLineOnView:(UIView *)lineView{
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    [shapeLayer setBounds:lineView.bounds];
    [shapeLayer setPosition:CGPointMake(CGRectGetWidth(lineView.frame) / 2, CGRectGetHeight(lineView.frame))];
    [shapeLayer setFillColor:[UIColor clearColor].CGColor];
    //  设置虚线颜色为blackColor
    [shapeLayer setStrokeColor:[UIColor colorWithString:@"#E4E4E4"].CGColor];
    //  设置虚线宽度
    [shapeLayer setLineWidth:CGRectGetHeight(lineView.frame)];
     
    [shapeLayer setLineJoin:kCALineJoinRound];
    //  设置线宽，线间距
    [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:7], [NSNumber numberWithInt:7], nil]];
    //  设置路径
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, 0, 0);
    CGPathAddLineToPoint(path, NULL,CGRectGetWidth(lineView.frame), 0);
    [shapeLayer setPath:path];
    CGPathRelease(path);
    //  把绘制好的虚线添加上来
    [lineView.layer addSublayer:shapeLayer];
}


@end
